<template>
  <MyDrawer ref="myRef" title="状态详情" @submit="submit" :disabled="false" width="30%">
    <el-form :model="drawerProps.row" :rules="rules" label-width="100" ref="formRef">
      <el-form-item label="状态名称" prop="name">
        <el-input v-model="drawerProps.row.name"></el-input>
      </el-form-item>
      <el-form-item label="背景颜色" prop="backColor">
        <el-color-picker v-model="drawerProps.row.backColor" popper-class="hex" size="large"></el-color-picker>
      </el-form-item>
      <el-form-item label="字体颜色" prop="textColor">
        <el-color-picker v-model="drawerProps.row.textColor" popper-class="hex" size="large"></el-color-picker>
      </el-form-item>
      <el-form-item label="状态码" prop="statusCode">
        <el-input-number :min="1" :max="10" v-model="drawerProps.row.statusCode"></el-input-number>
      </el-form-item>
      <el-form-item label="预览">
        <div v-show="drawerProps.row.name !== ''">
          <span class="px-5px py-2px" :style="{ backgroundColor: drawerProps.row.backColor, color: drawerProps.row.textColor }">{{
            drawerProps.row.name
          }}</span>
        </div>
      </el-form-item>
    </el-form>
  </MyDrawer>
</template>

<script setup lang="ts">
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ref } from "vue";
import { sellStatus } from "@/api/interface/sellStatus";
import { JustCanChinese, validHex } from "@/utils/eleValidate";
import { ElMessage, FormInstance, FormRules } from "element-plus";

const rules: FormRules = {
  name: [
    { required: true, validator: JustCanChinese },
    { max: 3, min: 1, message: "字符在1-3个字符之间" }
  ],
  backColor: [{ required: true, validator: validHex }],
  textColor: [{ required: true, validator: validHex }],
  statusCode: [{ required: true, message: "状态码不可为空" }]
};

interface DrawerProps {
  row: sellStatus;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}

const initData: sellStatus = {
  name: "",
  statusCode: 1,
  backColor: "#EFC250",
  textColor: "#000"
};

const drawerProps = ref<DrawerProps>({
  row: JSON.parse(JSON.stringify(initData))
});

const myRef = ref<InstanceType<typeof MyDrawer> | null>();

const acceptParams = (params: any) => {
  drawerProps.value = params;
  // console.log(drawerProps.value);
  myRef.value?.acceptParams();
};

const formRef = ref<FormInstance>();

const submit = () => {
  if (!formRef.value) return;
  formRef.value?.validate(async valid => {
    if (valid) {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success("成功");
      await drawerProps.value.getTable!();
      myRef.value?.close();
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style></style>
